package com.whitlock.backend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.github.pagehelper.PageHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whitlock.backend.domain.TKPage;
import com.whitlock.backend.entity.TKUser;
import com.whitlock.backend.exception.BusinessServiceException;
import com.whitlock.backend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Whitlock
 * @date 2020/7/14   4:00 下午
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理", value = "用户管理")
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation(value = "用户列表", notes = "用户列表")
    @RequestMapping("/getPageListUser")
    public TKPage<TKUser> getPageListUser(@ApiParam(name = "userName",value = "登录名")@RequestParam(value = "userName",defaultValue = "",required = false)String userName,
        @ApiParam(name = "pageNum",value = "当前页")@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
        @ApiParam(name = "pageSize",value = "页数")@RequestParam(value = "pageSize",defaultValue = "10")int pageSize){
        IPage<TKUser> page = new Page<>(pageNum, pageSize);
        List<TKUser> tkUserList=new ArrayList<>();
        if(StringUtils.isEmpty(userName)){
            tkUserList=userService.page(page).getRecords();
        }else {
            tkUserList=userService.page(page,Wrappers.<TKUser>query().like("user_name",userName)).getRecords();
        }
        return new TKPage<TKUser>(page.getTotal(),tkUserList,pageNum,pageSize);
    }

    @ApiOperation(value = "新增用户", notes = "新增用户")
    @RequestMapping("/addTKUser")
    public TKUser addTKUser(@RequestBody TKUser tkUser){
        boolean result=userService.save(tkUser);
        if(result){
            return tkUser;
        }else {
            throw new BusinessServiceException("参数错误");
        }
    }

    @ApiOperation(value = "修改用户", notes = "修改用户")
    @RequestMapping("/updateTKUser")
    public TKUser updateTKUser(@RequestBody TKUser tkUser){
        boolean result=userService.updateById(tkUser);
        if(result){
            return tkUser;
        }else {
            throw new BusinessServiceException("参数错误");
        }
    }

    @ApiOperation(value = "删除用户", notes = "删除用户")
    @RequestMapping("/deleteTKUser/{userId}")
    public String deleteTKUser(@PathVariable String userId){
        boolean result=userService.removeById(userId);
        if(result){
            return userId;
        }else {
            throw new BusinessServiceException("参数错误");
        }
    }

}
